<?php
/**
 * 同步处理 api
 */
namespace app\services;

use app\utils\Functions as F;

class AccuenService extends ApiService {
    public $Accuenconf = null;

    public function __construct($ssp) {
        parent::__construct($ssp);
        $this->sspconf = $this->conf[$ssp];
    }

    public $bannerTransMatrix = [
        'name' => 'title',
        'media_id' => ['media_id', 'return (string) $v;'],
        'base_price' => ['bidfloor', 'return round($v/100, 2);'],
        'ad_network_adspace_id' => 'adspace_id',
        'position' => 'screen_level',
        'format_list' => ['adformat', 'return implode(",", $v);'],
        'category_id' => 'vertical',
        'width' => 'width',
        'height' => 'height',
        'ad_form'               => 'adform',
    ];

    public $videoTransMatrix = [
        'name' => 'title',
        'media_id' => 'media_id',
        'base_price'            => 'bidfloor',
        'ad_network_adspace_id' => 'adspace_id',
        'format_list' => ['adformat', 'return implode(",", $v);'],
        'width' => 'width',
        'height' => 'height',
        'min_duration' => 'min_duration',
        'max_duration' => 'max_duration',
        'ad_form' => 'adform',
    ];

    public $mobileTransMatrix = [
        'name' => 'title',
        'type' => 'type',
        'media_id' => 'media_id',
        'ad_network_adspace_id' => 'adspace_id',
        'width' => 'width',
        'height' => 'height',
        'size_form'             => 'adform',
        'position'              => 'screen_level',
        'category_id'           => 'vertical',
        'app_category'          => 'app_category',
        'ext_width'             => 'ext_width',
        'ext_height'            => 'ext_height',
    ];

    public $mobileVideoTransMatrix = [
        'name'                  => 'title',
        'media_id'              => 'media_id',
        'base_price'            => ['bidfloor', 'return round($v/100, 2);'],
        'city_group'            => 'city_group_price',
        'ad_network_adspace_id' => 'adspace_id',
        'format_list'           => ['adformat', 'return implode(",", $v);'],
        'width'                 => 'width',
        'height'                => 'height',
        'min_duration'          => 'min_duration',
        'max_duration'          => 'max_duration',
        'ad_form'               => 'adform',
        'platform'              => ['os', 'return $v+1;'],
    ];

    public function syncAdspace($type) {
        $ads = $this->getAdspaceInfo($type);
        if (!$ads) return false;
        $ads = json_decode($ads, true);
        $type == 'bannerAdspace' && $form = 1;
        $type == 'videoAdspace' && $form = 2;
        $type == 'mobileAdspace' && $form = 3;
        $type == 'mobileVideoAdspace' && $form = 4;
        $this->addAdspace($ads, $form);
    }

    public function addAdspace(array $adspaces, $form) {
        if ($form == 1) {
            $table = 'Adspace';
            $adspaces = F::fieldsMap($adspaces, $this->bannerTransMatrix);
        } else if ($form == 2) {
            $table = 'VideoAdspace';
            $adspaces = $this->mapVideoAdspace($adspaces);
        } else if ($form == 3) {
            $table = 'MobileAdspace';
            $adspaces = $this->mapMobileAdspaces($adspaces);
        } else if ($form == 4) {
            $table = 'MobileVideoAdspace';
            $adspaces = F::fieldsMap($adspaces, $this->mobileVideoTransMatrix);
        }
        $this->update($table, ['ad_network_id' => $this->adnetworkId], ['status'=>1]);
        foreach ($adspaces as $adspace) {
            $adspace['ad_network_id'] = $this->adnetworkId;
            $adspace['ad_network_adspace_id'] = (string) $adspace['ad_network_adspace_id'];
            $adspace['base_price'] = (string) $adspace['base_price'];
            $adspace['status'] = 0;
            $pk = ['ad_network_id'         => $this->adnetworkId, 
                   'ad_network_adspace_id' => $adspace['ad_network_adspace_id']];
            $save = $this->saveOn($table, $pk, $adspace);
        }
    }

    /**
     * 获取配置文件中的 api 地址
     */
    public function getApiUrl($type) {
        if (in_array(array_keys($this->sspconf), $type)) {
            return $this->sspconf[$type];
        }
        return '';
    }

    /**
     * upload/update creative to ssp
     */
    public function sendCreative($data, $action='upload', $type) {
        $url = $this->getApiActionUrl($action, $type);
        return $this->post($url, $data);
    }

    public function getCreative($query, $action, $type) {
        $url = $this->getApiActionUrl($action, $type);
        return $this->getApiContent($url.$query);
    }

    public function getApiActionUrl($action, $type) {
        switch ($action) {
            case 'upload':
                $type == 'banner' && $api = 'bannerCreativeUpload';
                $type == 'video' && $api = 'videoCreativeUpload';
                $type == 'web' && $api = 'mobileWebCreativeUpload';
                $type == 'app' && $api = 'mobileAppCreativeUpload';
                $type == 'mobile_video' && $api = 'mobileVideoCreativeUpload';
                break;
            case 'update':
                $type == 'banner' && $api = 'bannerCreativeUpdate';
                $type == 'video' && $api = 'videoCreativeUpdate';
                $type == 'web' && $api = 'mobileWebCreativeUpdate';
                $type == 'app' && $api = 'mobileAppCreativeUpdate';
                $type == 'mobile_video' && $api = 'mobileVideoCreativeUpdate';
                break;
            case 'status':
                $type == 'banner' && $api = 'bannerCreativeStatus';
                $type == 'video' && $api = 'videoCreativeStatus';
                $type == 'web' && $api = 'mobileCreativeStatus';
                $type == 'app' && $api = 'mobileCreativeStatus'; 
                $type == 'mobile_video' && $api = 'mobileVideoCreativeStatus';
                break;
            case 'get':
                $type == 'banner' && $api = 'bannerCreativeGet';
                $type == 'video' && $api = 'videoCreativeGet';
                $type == 'web' && $api = 'mobileCreativeGet';
                $type == 'app' && $api = 'mobileCreativeGet';
                $type == 'mobile_video' && $api = 'mobileVideoCreativeGet';
                break;
            default:
                $type == 'banner' && $api = 'bannerCreativeUpload';
                $type == 'video' && $api = 'videoCreativeUpload';
                $type == 'web' && $api = 'mobileWebCreativeUpload';
                $type == 'app' && $api = 'mobileAppCreativeUpload';
                $type == 'mobile_video' && $api = 'mobileVideoCreativeUpload';
                break;
        }
        return $this->sspconf['domain'].$this->sspconf[$api];
    }

    private function mapMobileAdspaces($adspaces) {
        $result = [];
        foreach ($adspaces as $adspace) {
            $data['base_price'] = round($adspace['bidfloor']/100, 2);
            $data['format_list'] = implode(",", $adspace['adformat']);
            $data['category_id'] = 0;
            $this->setValues($data, $adspace, $this->mobileTransMatrix);
            $size[] = $data['width'].'*'.$data['height'];
            if (isset($data['ext_width'])) {
                $data['ext_width'] = explode(',', $data['ext_width']);
                $data['ext_height'] = explode(',', $data['ext_height']);
                foreach ($data['ext_width'] as $key => $value) {
                    $size[] = $value.'*'.$data['ext_height'][$key];
                }
                unset($data['ext_width']);
                unset($data['ext_height']);
            }
            $data['ext_size'] = implode(',', $size);
            $result[] = $data;
            $data = [];
            $size = [];
        }
        return $result;
    }

    private function setValues(&$data, $json, $maps) {
        foreach ($maps as $k => $v) {
            if(isset($json[$v])) {
                $data[$k] = $json[$v];
            }
        }
    }

    private function mapVideoAdspace(&$adspaces) {
        foreach ($adspaces as &$adspace) {
            $prices = explode(",", $adspace['bidfloor']);
            foreach ($prices as &$price) {
                $price = round($price/100, 2);
            }
            $adspace['bidfloor'] = implode(",", $prices);
        }
        $adspaces = F::fieldsMap($adspaces, $this->videoTransMatrix);
        return $adspaces;
    }

    public function syncPmp() {
        $url = $this->formUrl('pmp');
        $pmps = $this->getApiContent($url);
        $pmps = json_decode($pmps, true);
        if ($pmps) $this->expireAllPmps();
        foreach ($pmps as $pmp) {
            if (isset($pmp['id']))
                unset($pmp['id']);
            $pk = ['guid' => $pmp['guid']];
            $save = $this->saveOn('FlowPmp', $pk, $pmp);
        }
        $url = $this->formUrl('pmpAdspace');
        $pmpAds = $this->getApiContent($url);
        $pmpAds = json_decode($pmpAds, true);
        foreach ($pmpAds as $pmpAd) {
            if (isset($pmpAd['id']))
                unset($pmpAd['id']);
            $pk = ['flow_pmp_guid' => $pmpAd['flow_pmp_guid'], 
                   'adspace_guid'  => $pmpAd['adspace_guid'],
                   'adspace_class_id' => $pmpAd['adspace_class_id'],
            ];
            $save = $this->saveOn('FlowPmpAdspaceMap', $pk, $pmpAd);
        }
    }

    public function expireAllPmps() {
        $sql = "update {{%flow_pmp}} set status = 0";
        $this->executeSql($sql);
        $sql = "update {{%flow_pmp_adspace_map}} set status = 0";
        $this->executeSql($sql);
    }

    public function syncMediaList() {
        $url = $this->formUrl('mediaList');
        $mediaLists = $this->getApiContent($url);
        $mediaLists = json_decode($mediaLists, true);   
        foreach ($mediaLists as $media) {
            $data['ad_network_id'] = 1;
            $data['media_id'] = $media['guid'];
            $data['media_name'] = $media['name'];
            $this->saveOn('AdnetworkMedia', $data, $data);
        }
    }
}//end of SspService declaration
